package com.rede.didiok.community.event.listener;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.TypeReference;
import com.rede.didiok.common.convert.AggEsDocConvert;
import com.rede.didiok.common.dto.community.UserMomentDto;
import com.rede.didiok.common.dto.user.UserDto;
import com.rede.didiok.common.enums.AuditStatusEnum;
import com.rede.didiok.common.enums.BusinessTypeEnum;
import com.rede.didiok.common.enums.OperateEnum;
import com.rede.didiok.common.enums.PublishEnum;
import com.rede.didiok.common.exception.exceptionType.FeignException;
import com.rede.didiok.common.executor.AsyncService;
import com.rede.didiok.common.feign.UserFeignClient;
import com.rede.didiok.common.schema.AggEsDoc;
import com.rede.didiok.common.utils.R;
import com.rede.didiok.common.utils.business.RabbitMqUtil;
import com.rede.didiok.community.entity.UserMomentEntity;
import com.rede.didiok.community.event.momentEvent.*;
import com.rede.didiok.community.service.UserMomentService;

@Component
@Slf4j
public class MomentListener {

    /**
     * 用户服务
     */
    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 简易的mq邮件封装工具类
     */
    @Resource
    private RabbitMqUtil rabbitMqUtil;

    /**
     * 异步执行服务
     */
    @Resource
    private AsyncService asyncService;

    /**
     * 动态服务
     */
    @Resource
    private UserMomentService userMomentService;

    /**
     * 动态审核事件
     *
     * @param event
     */
    @EventListener(value = MomentAuditEvent.class)
    public void audit(MomentEvent event) {
        UserMomentEntity userMoment = (UserMomentEntity) event.getSource();
        /**
         * 发送邮件
         */
        if (userMoment.getCreateUserUid() != null) {
            R result = userFeignClient.getUserById(userMoment.getCreateUserUid());
            UserDto user;
            if(result.getCode()==0){
                user = result.getData(new TypeReference<UserDto>(){});
            }else {
                // 获取异常信息
                String msg = result.getData("msg",new TypeReference<String>(){});
                throw new FeignException("feign调用异常（根据用户id找用户）："+msg);
            }
            StringBuilder text = new StringBuilder();
            text.append(String.format("<p>可爱的博主%s,您的动态</p>", user.getNickname()));
            if (AuditStatusEnum.REJECT.equals(userMoment.getAuditStatus())) {
                text.append("审核未通过,审核原因为" + userMoment.getRejectReason());
                rabbitMqUtil.sendSimpleEmail(user.getEmail(), text.toString());
            } else if (AuditStatusEnum.AGREE.equals(userMoment.getAuditStatus())) {
                text.append("审核已通过");
                rabbitMqUtil.sendSimpleEmail(user.getEmail(), text.toString());
            } else {
                log.error("审核状态异常,稿件为{}", userMoment.getUid());
            }
        }
        this.syncAggEsDoc(userMoment, OperateEnum.EDIT);
    }

    /**
     * 新增事件
     *
     * @param event
     */
    @EventListener(value = MomentAddEvent.class)
    public void add(MomentEvent event) {
        UserMomentEntity userMoment = (UserMomentEntity) event.getSource();

        if (AuditStatusEnum.AGREE.equals(userMoment.getAuditStatus()) && PublishEnum.PUBLISH.equals(userMoment.getIsPublish())) {
            // 增加用户积分
//            userService.addUserCredits(CreditTypeEnum.Moment.getAction(), null, userMoment.getUid(), userMoment.getUserUid());
            // 通知关注的用户，发送动态通知
            asyncService.executeAsyncBusinessNotice(false, userMoment.getCreateUserUid(), userMoment.getUid(), BusinessTypeEnum.MOMENT.getCode());
        }
        // 发送后台站内信通知
        asyncService.executeAsyncBusinessBlackNotice(false, userMoment.getCreateUserUid(), userMoment.getUid(), BusinessTypeEnum.MOMENT.getCode(), userMoment.getContent());
        // 更新ES索引
        this.syncAggEsDoc(userMoment, OperateEnum.ADD);
    }

    @EventListener(value = MomentEditEvent.class)
    public void edit(MomentEvent event) {
        UserMomentEntity userMoment = (UserMomentEntity) event.getSource();
        this.syncAggEsDoc(userMoment, OperateEnum.EDIT);
    }

    @EventListener(value = MomentDeleteEvent.class)
    public void delete(MomentEvent event) {
        UserMomentEntity userMoment = (UserMomentEntity) event.getSource();
//        if (StringUtils.isNotEmpty(userMoment.getCreateUserUid())) {
//            // 动态删除，扣除积分
//            userService.addUserCredits(CreditTypeEnum.Delete_Moment.getAction(), null, userMoment.getUid(), userMoment.getUserUid());
//        }
        this.syncAggEsDoc(userMoment, OperateEnum.DELETE);
    }

    private void syncAggEsDoc(UserMomentEntity userMoment, OperateEnum operate) {
        UserMomentDto momentDto = new UserMomentDto();
        BeanUtils.copyProperties(userMoment,momentDto);
        AggEsDoc aggEsDoc = AggEsDocConvert.convertMoment(momentDto);
//        if (EOperate.ADD == operate && aggEsDoc.getOid() == null) {
//            log.info("syncAggEsDoc: aggEsDoc oid is nil");
//            UserMoment userMomentTemp = userMomentService.getById(userMoment.getUid());
//            if (userMomentTemp != null) {
//                aggEsDoc.setOid(userMomentTemp.getOid());
//            }
//            /**
//             * 更新索引
//             */
//        }
        asyncService.executeAsyncUpdateEsAndRedis(aggEsDoc, operate);
    }


}
